package com.karlis.service;

import java.util.List;
import java.util.Set;
 
import javax.annotation.Resource;
 
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.karlis.domain.Item;
import com.karlis.domain.Warehouse;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("warehouseService")
@Transactional
public class WarehouseService {
	
	protected static Logger logger = Logger.getLogger("service");
	
	@Resource(name="sessionFactory")
	 private SessionFactory sessionFactory;
	
	public List<Warehouse> getAll() {
		  logger.debug("Retrieving all warehouses");
		   
		  // Retrieve session from Hibernate
		  Session session = sessionFactory.getCurrentSession();
		 
		  // Create a Hibernate query (HQL)
		  Query query = session.createQuery("FROM Warehouse");
		   
		  // Retrieve all
		  return  query.list();
		 }
	public List<Warehouse> getItems() {
		
		
		return null;
	}
	
	public Warehouse get( Integer id ) {
	  // Retrieve session from Hibernate
	  Session session = sessionFactory.getCurrentSession();
		   
	  // Retrieve existing person
	  // Create a Hibernate query (HQL)
	  Query query = session.createQuery("FROM Warehouse as p LEFT JOIN FETCH  p.items WHERE p.id="+id);
		   
	  return (Warehouse) query.uniqueResult();
	 }
	
	public void add(Warehouse warehouse) {
	  logger.debug("Adding new warehouse");
		   
	  // Retrieve session from Hibernate
	  Session session = sessionFactory.getCurrentSession();
		   
	  // Persists to db
	  session.save(warehouse);
	 }
	
	public void delete(Integer id) {
	  logger.debug("Deleting existing warehouse");
		   
	  // Retrieve session from Hibernate
	  Session session = sessionFactory.getCurrentSession();
		   
	  // Create a Hibernate query (HQL)
	  Query query = session.createQuery("FROM Warehouse as p LEFT JOIN FETCH  p.items WHERE p.id="+id);
		  
	  // Retrieve record
	  Warehouse warehouse = (Warehouse) query.uniqueResult();
		   
	  Set<Item> items =warehouse.getItems();
		   
	  // Delete person
	  session.delete(warehouse);
		   
	  // Delete associated credit cards
	  for (Item item: items) {
	   session.delete(item);
	  }
	 }
	
	public void edit(Warehouse warehouse) {
	  logger.debug("Editing existing warehouse");
		   
	  // Retrieve session from Hibernate
	  Session session = sessionFactory.getCurrentSession();
		   
	  // Retrieve existing person via id
	  Warehouse existingWarehouse = (Warehouse) session.get(Warehouse.class, warehouse.getId());
		   
	  // Assign updated values to this person
	  existingWarehouse.setName(warehouse.getName());
	  existingWarehouse.setAddress(warehouse.getAddress());
	  existingWarehouse.setManager(warehouse.getManager());
		 
	  // Save updates
	  session.save(existingWarehouse);
	 }

}
